package org.demo.cnck.controller.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.demo.cnck.controller.error.UnauthorizedException;
import org.demo.cnck.controller.vm.HttpMessage;
import org.demo.cnck.controller.vm.HttpResult;
import org.demo.cnck.dao.constant.SystemConstant;
import org.demo.cnck.dao.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Aspect
@Component
public class AccessControlAop {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private HttpSession httpSession;
    @Autowired
    private HttpServletRequest request;

    @Pointcut("execution(public * org.demo.cnck.controller.api..*.*(..))")
    private void apiPointcut() {
    }

    @Before("apiPointcut()")
    private void doBefore(JoinPoint joinPoint) {
        String servletPath = request.getServletPath();
        if (antPathMatcher.match("/system/**", servletPath)) {
            return;
        }


        User user = (User) httpSession.getAttribute(SystemConstant.USER_SESSION_KEY);
        if (null == user) {
            throw new UnauthorizedException("用户尚未登录");
        }
    }

    @Around("apiPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object proceed = point.proceed();
        if (proceed instanceof ResponseEntity) {
            ResponseEntity re = (ResponseEntity) proceed;
            Object body = re.getBody();
            HttpStatus responsCode = re.getStatusCode();
            HttpResult.HttpResultBuilder resultBuilder = HttpResult.builder();
            if (responsCode.equals(HttpStatus.OK) || responsCode.equals(HttpStatus.CREATED)) {
                resultBuilder.code(20);
                String message = body instanceof HttpMessage ? ((HttpMessage) body).getMessage() : "操作成功";
                resultBuilder.message(message);
                resultBuilder.data(body);
                return ResponseEntity.ok(resultBuilder.build());
            }

            if (!responsCode.equals(HttpStatus.OK) || !responsCode.equals(HttpStatus.CREATED)) {
                HttpMessage hm = (HttpMessage) body;
                resultBuilder.code(hm.getCode());
                resultBuilder.message(hm.getMessage());
                resultBuilder.data(hm.getMessage());
                resultBuilder.result(HttpResult.Result.FAIL);
                return ResponseEntity.ok(resultBuilder.build());
            }
        }
        return proceed;
    }


}
